<template>
  <div class="map-wrap">
    <div class="btns">
      <div class="left">
        <el-tooltip class="cn-btns" effect="dark"
                    content="点击，在地图上点击绘制区域，双击地图完成绘制，进入编辑状态"
                    placement="top-start">
          <el-button type="primary" @click="addRectangle()" icon="el-icon-question" size="mini">画配送区域</el-button>
        </el-tooltip>
        <el-tooltip v-if="isShowBtns" class="cn-btns" effect="dark"
                    content="点击，主动编辑已完成的区域" placement="top-start">
          <el-button type="primary" @click="eidtRectangle()" icon="el-icon-question" size="mini">编辑配送区域</el-button>
        </el-tooltip>
        <el-tooltip v-if="isShowBtns" class="cn-btns" content="点击，使编辑中的区域生效" placement="top-start">
          <el-button type="primary" @click="endEidtRectangle()" icon="el-icon-question" size="mini">结束编辑</el-button>
        </el-tooltip>
      </div>
      <input id='searchArea' v-model="searchName" placeholder="位置模糊查询" class="input-with-select" />
    </div>
    <div id="container" class="delivery-map" :class="{'crosshair': eidtRectanglePoint }"></div>
  </div>
</template>

<script>
  import AMap from 'AMap'
  export default {
    props: {
      distrange: {
        type: String,
        default: ''
      },
      deliveryArea: {
        type: String,
        default: ''
      },
      agentArea: {
        type: String,
        defalut: ''
      },
      search: {
        type: String,
        defalut: ''
      }
    },
    data() {
      return {
        searchName: '',
        deliveryPolygon1Id: null, // 配送围栏
        agentAreaPolygonlId: null, // 代理商区域
        mouseTool: null,//鼠标工具
        polygonEditor: null,//编辑工具
        isShowBtns: false,//显示按钮
        map: null,
        eidtRectanglePoint: false
      }
    },
    watch: {
      search(val) {
        this.searchName = val
      },
      agentArea(val) {
        this.showAgentArea(val)
      },
      deliveryArea(val) {
        this.showDeliveryArea(val)
      }
    },
    methods: {
      init: function () {  //初始化地图
        this.map = new AMap.Map('container', {
          resizeEnable: true,
          zoom: 16,
          center: [116.397428, 39.90923] //初始化地图中心点
        })
        AMap.plugin(['AMap.ToolBar', 'AMap.Scale'], () => {
          this.map.addControl(new AMap.ToolBar())
          this.map.addControl(new AMap.Scale())
        })
        AMap.plugin(['AMap.Autocomplete','AMap.PlaceSearch'], () => {
          var autoOptions = { input: "searchArea" }
          var autocomplete= new AMap.Autocomplete(autoOptions)
          AMap.event.addListener(autocomplete, "select", (e) => {
            const pos = [e.poi.location.O,e.poi.location.P]
            this.map.setCenter(pos)
          })
        })
      },
      irregularPolygon(pos) { //验证是否边相交
        const lines = [] //多边形的所有边
        for (var i = 0; i < pos.length; i++) {
          if (i < pos.length - 1) {
            lines.push([pos[i], pos[i + 1]])
          } else {
            lines.push([pos[i], pos[0]])  //最后要给点连第一个点
          }
        }
        //其中一个变和所有边里判断 n*n循环
        let whetherTheIntersection = false
        lines.forEach((item, index1) => {
          lines.forEach((list, index2) => {
            //自己和自己不比较 ，也不和相邻的比较
            const comparison = () => {
              let ml = lines.length - 1
              if (index1 == index2) return false
              else {
                if (index1 == 0) {
                  if (index2 == 1 || index2 == ml) return false
                } else if (index1 == ml) {
                  if (index2 == 0 || index2 == (ml - 1)) return false
                } else {
                  if (index2 == 0) {
                    if (index1 == 1 || index1 == ml) return false
                  } else if (index2 == ml) {
                    if (index1 == ml - 1) return false
                  } else {
                    if (index1 == (index2 + 1) || (index1 == index2 - 1)) return false
                  }
                }
              }
              return true
            }
            if (comparison()) {
              let p1 = item[0], p2 = item[1], p3 = list[0], p4 = list[1]
              let isPointInRing = AMap.GeometryUtil.doesSegmentsIntersect(p1, p2, p3, p4);
              if (isPointInRing) {
                whetherTheIntersection = true
                return false
              }
            }
          })
        })
        return whetherTheIntersection
      },
      eidtRectangle() { //编辑多边形
        if (this.polygonEditor) {
          this.polygonEditor.open()
          return false
        }
        this.polygonEditor = new AMap.PolyEditor(this.map, this.filterPolygon(this.deliveryPolygon1Id))
        this.polygonEditor.open()
      },
      endEidtRectangle() { //结束画多边形
        if (!this.polygonEditor) return false
        this.polygonEditor.close()
        let position = this.filterPolygon(this.deliveryPolygon1Id).getPath()
        let arr = [], arrForInPolygon = []
        position.forEach(item => {
          arr.push(`${item.O},${item.P}`)
          arrForInPolygon.push([item.O, item.P])
        })
        if (!this.irregularPolygon(arrForInPolygon)) {
          this.$emit('surDistrange', arr.join('|') + '|')
        } else {
          this.eidtRectangle()
          this.$alert('请绘制有规则的多边形（多边形任意边不相错）')
        }
      },
      addRectangle() {  //画多边形
        this.eidtRectanglePoint = true
        if (this.deliveryPolygon1Id) {
          this.removePolygon(this.deliveryPolygon1Id)
          this.deliveryPolygon1Id = null
        }
        this.isShowBtns = false
        if (this.mouseTool) this.mouseTool.close()
        if (this.polygonEditor) {
          this.polygonEditor.close()
          this.polygonEditor = ''
        }
        this.mouseTool = new AMap.MouseTool(this.map)
        const drawPolygon = this.mouseTool.polygon()
        AMap.event.addListener(this.mouseTool, 'draw', e => {
          this.isShowBtns = true
          this.mouseTool.close()
          this.deliveryPolygon1Id = e.obj._amap_id
          this.eidtRectangle()
          this.eidtRectanglePoint = false
        })
      },
      inPolygon(inPos, polygon) { //验证多边形是否在围栏内部
        let inPosition = false
        inPos.forEach(item => {
          var marker1InPolygon = polygon.contains(item)
          if (!marker1InPolygon) {
            inPosition = true
            return false
          }
        })
        return inPosition
      },
      searlDistrange(pos) { // 过滤后台存储的经纬度
        const positionArr = []
        let position = pos.trim()
        let lastStr = position.charAt(position.length - 1)
        if (lastStr == '|') {
          position = position.substring(0, position.lastIndexOf('|'))
        }
        position.split('|').forEach(item => {
          positionArr.push(item.split(','))
        })
        return positionArr
      },
      filterPolygon(id) { // 查找队友的多边形
        const overlays = this.map.getAllOverlays('polygon')
        const index = overlays.findIndex(i => id == i._amap_id)
        if (index > -1) return overlays[index]
        else return null
      },
      removePolygon(id) { // 删除指定多边形
        const overlays = this.map.getAllOverlays('polygon')
        const index = overlays.findIndex(i => id == i._amap_id)
        if (index > -1) this.map.remove(overlays[index])
      },
      showDeliveryArea(pos) { // 显示代理商配送区域
        if (this.deliveryPolygon1Id) {
          this.removePolygon(this.deliveryPolygon1Id)
          this.deliveryPolygon1Id = null
        }
        const polygon1 = new AMap.Polygon({
          map: this.map,
          path: this.searlDistrange(pos),
          strokeColor: "#3c48f5",
          strokeOpacity: 1,
          strokeWeight: 2,
          fillColor: "#448ef5",
          fillOpacity: 0.35
        })
        this.deliveryPolygon1Id = polygon1._amap_id
        this.isShowBtns = true
        this.map.setFitView()
      },
      showAgentArea(pos) { // 显示代理商区域
        if (this.agentAreaPolygon1Id) {
          this.removePolygon(this.agentAreaPolygon1Id)
          this.agentAreaPolygon1Id = null
        }
        const polygon1 = new AMap.Polygon({
          map: this.map,
          path: this.searlDistrange(pos),
          strokeColor: "#ff232f",
          strokeOpacity: 1,
          strokeWeight: 2,
          fillColor: "#6bf517",
          fillOpacity: 0.35
        })
        this.agentAreaPolygon1Id = polygon1._amap_id
        this.map.setFitView()
      }
    },
    mounted() {
      this.init()
    }
  }
</script>
<style lang="scss">
  #searchArea {
    background-color: #fff;
    font-size: 15px;
    font-weight: 300;
    height: 20px;
    line-height: 20px;
    padding: 5px;
    text-overflow: ellipsis;
    width: 300px;
  }
  #searchArea:focus {
    border-color: #4d90fe;
  }
</style>
<style lang="scss" scoped>
  .map-wrap{
    position: relative;
    width: 100%;
    .btns{
      position: absolute;
      z-index: 9;
      left: 0;
      top: 0;
      right: 0;
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 40px;
      padding: 0 10px 0 70px;
    }
    .delivery-map{
      width: 100%;
      height: 100%;
      &.crosshair{
        cursor: crosshair;
      }
    }
  }
</style>
